package cn.felord.verse.configure;

import cn.felord.common.kogito.dmn.DmnApplicationBuilder;
import cn.felord.common.kogito.dmn.DmnApplicationContext;
import cn.felord.common.kogito.dmn.SimpleDecisionConfig;
import org.kie.dmn.api.core.event.DMNRuntimeEventListener;
import org.kie.kogito.Addons;
import org.kie.kogito.Application;
import org.kie.kogito.Config;
import org.kie.kogito.KogitoConfig;
import org.kie.kogito.KogitoGAV;
import org.kie.kogito.StaticConfig;
import org.kie.kogito.config.ConfigBean;
import org.kie.kogito.config.StaticConfigBean;
import org.kie.kogito.decision.DecisionConfig;
import org.kie.kogito.decision.DecisionEventListenerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * @author dax
 * @since 2023/12/28
 */
@Configuration(proxyBeanMethods = false)
public class DmnConfiguration {

    @Value("${kogito.service.url:#{null}}")
    private Optional<String> kogitoService;

    @Value("${kogito.messaging.as-cloudevents:#{true}}")
    private boolean useCloudEvents;

//    @Value("${kogito.jackson.fail-on-empty-bean:#{false}}")
//    private boolean failOnEmptyBean;


    @Bean
    ConfigBean configBean() {
        KogitoGAV gav = new KogitoGAV("cn.felord",
                "dmn-kogito-spring-boot-samples",
                "0.0.1-SNAPSHOT");
        return new StaticConfigBean(kogitoService.orElse(""), useCloudEvents, gav);
    }

    @Bean
    Config appAddonsConfig(Collection<KogitoConfig> configs) {
        KogitoConfig[] configsArray = configs.toArray(new KogitoConfig[0]);
        return new StaticConfig(new Addons(Set.of()), configsArray);
    }


    @Bean
    DecisionConfig decisionConfig(List<DecisionEventListenerConfig> decisionEventListenerConfigs,
                                  List<DMNRuntimeEventListener> dmnRuntimeEventListeners) {
        return new SimpleDecisionConfig(decisionEventListenerConfigs, dmnRuntimeEventListeners);
    }

    /**
     * 初始化应用，直接使用是静态的 动态需要使用{@link DmnApplicationContext}
     *
     * @param config         config
     * @param decisionConfig decisionConfig
     * @return Application
     */
    @Bean(DmnApplicationContext.DMN_APPLICATION_BEAN_NAME)
    Application dmnApplication(Config config, DecisionConfig decisionConfig) throws IOException {
        //todo dmn 文件校验
        String locationPattern = "classpath:**.dmn";
//        String locationPattern = "file:C:/Users/Administrator/Desktop/mat/**.dmn";
        return DmnApplicationBuilder.dmnApplicationFromLocation(config, decisionConfig, locationPattern);
    }

    @Bean
    DmnApplicationContext kogitoApplicationContext() {
        return new DmnApplicationContext();
    }

}
